package qeb.handheldmedical.exam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import qeb.handheldmedical.R;
import qeb.handheldmedical.adapter.ExamItemAdapter;
import qeb.handheldmedical.adapter.SlideListView;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.ExamChoose;
import qeb.handheldmedical.model.ExamItem;
import qeb.handheldmedical.model.User;
import android.R.bool;
import android.R.integer;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author 作者(dugaoyi) E-mail:dugaoyi@163.com
 * @version 创建时间：2016年8月30日 下午2:14:28
 * @declaration 在线作答
 */
public class Examination extends Activity {

	public int colseFlag = 0;// 关闭标志
	User usr = new User();
	private String examID, examType, examTitle;
	private Button btn_examok, btn_examprev, btn_examnext, tv_count;
	private TextView tv_examName, tv_examItem, tv_time;
	private int rcount = -1;// 30分钟
	private Timer timer = null;
	private TimerTask task;
	private List<ExamItem> lexamItem = new ArrayList<ExamItem>();
	private SlideListView slidelvexam;
	private ExamItemAdapter adapter;
	private int examItemIndex = 0;
	private Toast tt;
	private MultiDialog mDialog;
	private PopupWindow mPopupWindow;
	private GridView gv = null;
	// 手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
	float x1 = 0;
	float x2 = 0;
	float y1 = 0;
	float y2 = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		super.onCreate(savedInstanceState);
		usr = (User) getIntent().getSerializableExtra("userinfo");
		examID = (String) getIntent().getSerializableExtra("examID");
		examType = (String) getIntent().getSerializableExtra("examType");
		examTitle = (String) getIntent().getSerializableExtra("examTitle");
		setContentView(R.layout.examination);

		CheckExam();// 验证有没有试卷，答题是不是超过3次
		btn_examok = (Button) findViewById(R.id.btn_examok);
		btn_examok.setOnClickListener(MyOnClickListener);
		tv_examName = (TextView) findViewById(R.id.tv_examName);
		tv_examName.setText(examTitle);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_count = (Button) findViewById(R.id.tv_count);
		tv_count.setOnClickListener(MyOnClickListener);
		slidelvexam = (SlideListView) findViewById(R.id.slidelvexam);
		slidelvexam.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 触摸按下时的操作
					x1 = event.getX();
					y1 = event.getY();
					break;
				case MotionEvent.ACTION_MOVE:
					// 触摸移动时的操作

					break;
				case MotionEvent.ACTION_UP:
					// 触摸抬起时的操作
					x2 = event.getX();
					y2 = event.getY();
					// 向上滑
					if (y1 - y2 > 50) {

					}
					// 向下滑
					else if (y2 - y1 > 50) {

					}
					// 向左滑
					else if (x1 - x2 > 25) {
						// 下一题
						btn_examnext.performClick();
					}
					// 向右滑
					else if (x2 - x1 > 25) {
						// 上一题
						btn_examprev.performClick();
					}
					break;
				}
				return false;

			}
		});
		tv_examItem = (TextView) findViewById(R.id.tv_examItem);
		btn_examprev = (Button) findViewById(R.id.btn_examprev);
		btn_examprev.setSelected(false);
		btn_examprev.setOnClickListener(MyOnClickListener);
		btn_examnext = (Button) findViewById(R.id.btn_examnext);
		btn_examnext.setOnClickListener(MyOnClickListener);

		SelectChoose();
	}

	private void BandGridView(View exam_popunwindwow) {
		gv = (GridView) exam_popunwindwow.findViewById(R.id.gvExamItem);

		ArrayList<HashMap<String, Object>> al = new ArrayList<HashMap<String, Object>>();
		for (ExamItem exam : lexamItem) {
			HashMap<String, Object> map = new HashMap<String, Object>();

			List<Integer> chvalues = exam.getChooseValue();
			if (null == chvalues || chvalues.size() == 0) {

				map.put("no",
						"<font color=\"#FF4500\">×</font>第"
								+ String.valueOf(lexamItem.indexOf(exam) + 1)
								+ "题");
			} else {

				map.put("no",
						"<font color=\"#aabb00\">√</font>第"
								+ String.valueOf(lexamItem.indexOf(exam) + 1)
								+ "题");
			}

			al.add(map);
		}
		SimpleAdapter sa = new SimpleAdapter(this, al,
				R.layout.adapter_exam_popitem, new String[] { "no" },
				new int[] { R.id.ItemNo }) {
			@Override
			public void setViewText(TextView v, String text) {
				// TODO Auto-generated method stub
				v.setText(Html.fromHtml(text));
				// super.setViewText(v, Html.fromHtml(text));
			}

		};
		gv.setAdapter(sa);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> groupview, View view,
					int child, long position) {
				// TODO Auto-generated method stub
				examItemIndex = (int) position;
				SelectChoose();
				mPopupWindow.dismiss();
			}
		});
	}

	/**
	 * 验证有没有试卷，答题是不是超过3次
	 */
	private void CheckExam() {
		// TODO Auto-generated method stub

		Map<String, String> map = null;
		JSONArray JsonArray = null;
		if (usr.BQID != null) {

			map = new HashMap<String, String>();
			map.put("userid", usr.GH);
			map.put("examid", examID);
			JsonArray = WSHelper.getWebserviceFun("GetExamResult", map);
			// 考试超过3次不能作答
			if (null != JsonArray && JsonArray.length() >= 3) {
				stopTimer();
				mDialog = new MultiDialog(Examination.this,
						MultiDialog.DialogType.ALERT);
				mDialog.setTitle("系统提醒");
				mDialog.setMessage("此试卷您已经超过3次作答！");
				mDialog.setDialogKnowListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mDialog.cancel();
						colseFlag = 1;
						Examination.this.finish();
					}
				});
				mDialog.show();
			}
			// 读取数据
			else {
				// 读取数据
				getData();
				// 判断是否是空试卷
				if (null == lexamItem || lexamItem.size() == 0) {
					stopTimer();
					mDialog = new MultiDialog(Examination.this,
							MultiDialog.DialogType.ALERT);
					mDialog.setTitle("系统提醒");
					mDialog.setMessage("此试卷无考题项！");
					mDialog.setDialogKnowListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							mDialog.cancel();
							colseFlag = 1;
							Examination.this.finish();
						}
					});
					mDialog.show();
				}
			}

		}
		startTimer();
	}

	/**
	 * 开始定时
	 */
	private void startTimer() {
		if (timer == null) {
			timer = new Timer();
		}

		if (task == null) {
			task = new TimerTask() {
				@Override
				public void run() {
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				}
			};
		}

		if (timer != null && timer != null)
			timer.schedule(task, 1000, 1000);

	}

	/**
	 * 暂停定时
	 */
	private void stopTimer() {

		if (timer != null) {
			timer.cancel();
			timer = null;
		}

		if (task != null) {
			task.cancel();
			task = null;
		}
	}

	/**
	 * 绑定选择项数据
	 */
	private void SelectChoose() {
		// TODO Auto-generated method stub
		if (lexamItem != null && lexamItem.size() > 0) {

			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			// 试题条数
			tv_count.setText(String.valueOf(examItemIndex + 1) + "/"
					+ String.valueOf(lexamItem.size()));

			tv_examItem.setText(lexamItem.get(examItemIndex).getTitle());

			adapter = new ExamItemAdapter(lexamItem.get(examItemIndex)
					.getChooses().size(), Examination.this,
					lexamItem.get(examItemIndex));

			slidelvexam.setAdapter(adapter);

			slidelvexam.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					CheckBox chk = (CheckBox) view.findViewById(R.id.examchk);
					// 1＝单选，2＝多选，9＝阅读题
					int chkType = lexamItem.get(examItemIndex).getSubjectType();

					// 设置选项
					switch (chkType) {
					// 单选
					case 1:
						for (int i = 0; i < slidelvexam.getCount(); i++) {
							if (i == position) {
								chk.setChecked(!chk.isChecked());
							} else {
								CheckBox chktmp = (CheckBox) slidelvexam
										.getChildAt(i).findViewById(
												R.id.examchk);
								chktmp.setChecked(false);
							}
						}

						break;
					// 多选
					case 2:
						chk.setChecked(!chk.isChecked());
						break;
					// 阅读题
					case 9:

						break;
					default:
						break;
					}
					// 设置选中值
					List<Integer> checkValue = new ArrayList<Integer>();
					for (int i = 0; i < slidelvexam.getCount(); i++) {

						CheckBox chktmp = (CheckBox) slidelvexam.getChildAt(i)
								.findViewById(R.id.examchk);

						if (chktmp.isChecked()) {
							checkValue.add((i + 1));
						}
					}
					// 设置选中的值
					if (null != checkValue && checkValue.size() > 0)
						lexamItem.get(examItemIndex).setChooseValue(checkValue);

				}
			});

		}
	}

	/**
	 * 获取值
	 * 
	 * @throws JSONException
	 */
	private void getData() {
		if (usr.BQID != null) {

			Map<String, String> map = new HashMap<String, String>();
			map.put("userid", usr.GH);
			map.put("examid", examID);
			JSONArray JsonArray = WSHelper.getWebserviceFun(
					"GetPaperAndResult", map);
			if (null != JsonArray && JsonArray.length() > 0) {
				JSONObject jobj;
				try {
					jobj = JsonArray.getJSONObject(0);
					try {
						String[] timeStrings = jobj.getString("CREATETIME")
								.split("[|]");
						rcount = Integer.parseInt(timeStrings[1]);
						Log.v("Time", String.valueOf(rcount));
					} catch (Exception ex) {
						Log.v("Time", ex.getMessage());
						mDialog = new MultiDialog(Examination.this,
								MultiDialog.DialogType.CONFIRM);
						mDialog.setTitle("无效考试计时时间，考试将退出！");
						mDialog.setDialogGoListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								mDialog.cancel();
								colseFlag = 1;
								Examination.this.finish();
							}
						});

						mDialog.show();
					}
					// 试题列表字符串
					String SubjectIds = jobj.getString("SUBJECTIDS");
					String parentId = jobj.getString("PAPERID");
					if (!SubjectIds.equals("")) {
						map = new HashMap<String, String>();
						map.put("subjectids", SubjectIds);
						map.put("userid", usr.GH);
						map.put("resultid", "0");
						JsonArray = WSHelper.getWebserviceFun(
								"GetSubjectAndResults", map);

						if (null != JsonArray && JsonArray.length() > 0) {

							for (int i = 0; i < JsonArray.length(); i++) {
								ExamItem eItem = new ExamItem();
								jobj = JsonArray.getJSONObject(i);
								eItem.setDelFlag(Integer.valueOf(jobj
										.getString("DELFLAG")));
								eItem.setParentId(Integer.valueOf(parentId));
								eItem.setRightAnswer(jobj
										.getString("RIGHTANSWER"));
								eItem.setRightScores(Integer.valueOf(jobj
										.getString("RIGHTSCORES")));
								eItem.setSubjectId(Integer.valueOf(jobj
										.getString("SUBJECTID")));
								eItem.setSubjectType(Integer.valueOf(jobj
										.getString("SUBJECTTYPE")));
								eItem.setTitle(jobj.getString("TITLE"));

								List<ExamChoose> examChooses = new ArrayList<ExamChoose>();
								// 选项
								String strchoose = jobj.getString("CHOOSES");

								String[] chooses = StringUtils.split(strchoose,
										"|||");

								for (int j = 0; j < chooses.length; j++) {
									ExamChoose examChoose = new ExamChoose();
									examChoose.setItemName(chooses[j]);
									examChoose.setChangeValue(j + 1);
									examChooses.add(examChoose);
								}
								eItem.setChooses(examChooses);
								lexamItem.add(eItem);
							}
						}

					}

				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		}
	}

	/**
	 * 自定义按钮事件
	 */
	private OnClickListener MyOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			switch (v.getId()) {
			case R.id.btn_examok:

				int ltcount = 0;// 漏题数
				for (int i = 0; i < lexamItem.size(); i++) {
					ExamItem examItem = lexamItem.get(i);

					if (null == examItem.getChooseValue()
							|| examItem.getChooseValue().size() == 0) {
						ltcount++;
					}

				}

				mDialog = new MultiDialog(Examination.this,
						MultiDialog.DialogType.CONFIRM);
				mDialog.setTitle("系统提醒");

				if (ltcount > 0) {
					mDialog.setMessage("您有" + ltcount + "倒题未答，确认要提交试卷！");

				} else {
					mDialog.setMessage("您是否确认要提交些试卷！");
				}

				mDialog.setDialogGoListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mDialog.cancel();
						int state = SubmitExam();
						if (state == 1) {
							Examination.this.setResult(1, getIntent());
							colseFlag = 1;
							Examination.this.finish();
						}

					}
				});

				mDialog.show();

				break;
			case R.id.btn_examprev:
				if (tt != null)
					tt.cancel();
				examItemIndex--;
				btn_examnext.setSelected(true);
				if (examItemIndex < 0) {
					tt = Toast.makeText(Examination.this, "已是第一题",
							Toast.LENGTH_SHORT);
					tt.show();
					examItemIndex = 0;
					btn_examprev.setSelected(false);
				} else {
					btn_examprev.setSelected(true);
					SelectChoose();
				}
				break;
			case R.id.btn_examnext:
				btn_examprev.setSelected(true);
				examItemIndex++;
				if (tt != null)
					tt.cancel();
				// 判断当前是否是最后一条记录
				if (examItemIndex >= lexamItem.size()) {
					tt = Toast.makeText(Examination.this, "已是最后一题",
							Toast.LENGTH_SHORT);
					tt.show();
					examItemIndex = lexamItem.size() - 1;
					btn_examnext.setSelected(false);
				} else {
					btn_examnext.setSelected(true);
					SelectChoose();
				}
				break;
			case R.id.tv_count:
				showPopupWindow();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 提交试卷
	 */
	private int SubmitExam() {
		int state = 0;// 失败
		String strjson = "{\"EXAMID\":\"%s\",\"PAPERID\":\"%s\",\"RESULT\":\"%s\",\"JLRNAME\":\"%s\",\"RESULTID\":\"\",\"JLRID\":\"%s\"}";
		String PAPERID = "";
		String RESULT = "";
		String JLRNAME = usr.DNAME;
		String JLRID = usr.GH;

		for (int i = 0; i < lexamItem.size(); i++) {
			ExamItem examItem = lexamItem.get(i);
			if (i == 0)
				PAPERID = String.valueOf(examItem.getParentId());

			// 格式化选中值
			if (null != examItem.getChooseValue()
					&& examItem.getChooseValue().size() > 0) {
				for (int j = 0; j < examItem.getChooseValue().size(); j++) {
					RESULT += String.valueOf(examItem.getSubjectId()) + "$"
							+ String.valueOf(examItem.getChooseValue().get(j))
							+ "$" + String.valueOf(examItem.getSubjectType())
							+ "$" + examItem.getRightAnswer() + "$"
							+ String.valueOf(examItem.getRightScores()) + "*";
				}
			}

		}
		if (null != RESULT && !RESULT.equals("")) {

			// 定义json字符串
			strjson = String.format(strjson, examID, PAPERID, RESULT, JLRNAME,
					JLRID);

			if (usr.BQID != null) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("examResult", strjson);
				JSONArray resultJson = WSHelper.getWebserviceFun(
						"SaveExamResult", map);
				JSONObject xt;
				try {
					xt = resultJson.getJSONObject(0);
					if (xt.getString("pda_error_state").equals("0")) {
						Toast tt = Toast.makeText(Examination.this, "试卷提交成功！",
								Toast.LENGTH_SHORT);
						tt.show();
						state = 1;
					} else {
						tt = Toast.makeText(Examination.this,
								xt.getString("pda_error_message"),
								Toast.LENGTH_SHORT);
						tt.show();
						state = 0;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					tt = Toast.makeText(Examination.this, e.getMessage(),
							Toast.LENGTH_SHORT);
					tt.show();
					state = 0;
				}
			}

		} else {
			tt = Toast.makeText(Examination.this, "请您先作答再提交！",
					Toast.LENGTH_SHORT);
			tt.show();
			state = 0;
		}
		return state;
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (rcount == 0) {
					timer.cancel();
					// 提示时间已到
					tt = Toast.makeText(Examination.this, "考试时间已到，现自动提交！",
							Toast.LENGTH_SHORT);
					tt.show();
					int state = SubmitExam();
					// 退出作答
					if (state == 1) {
						// sendBroadcast();
						Examination.this.setResult(1, getIntent());
						colseFlag = 1;
						Examination.this.finish();
					}
				} else {
					rcount--;
					String strTime = secToTime(rcount);
					tv_time.setText(strTime + "分钟");
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 整形转时间 to xx:xx:xx
	 * 
	 * @param int
	 * @return xx:xx:xx
	 */
	private String secToTime(int time) {
		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (time <= 0)
			return "00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99:59:59";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
						+ unitFormat(second);
			}
		}
		return timeStr;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onGenericMotionEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onGenericMotionEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return super.onGenericMotionEvent(event);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub

		return super.onTouchEvent(event);
	}

	private String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}

	/**
	 * 打开试题列表
	 */
	private void showPopupWindow() {

		if (null == mPopupWindow || !mPopupWindow.isShowing()) {
			LayoutInflater mLayoutInflater = (LayoutInflater) this
					.getSystemService(LAYOUT_INFLATER_SERVICE);
			View exam_popunwindwow = mLayoutInflater.inflate(
					R.layout.exam_item_popwin, null);
			BandGridView(exam_popunwindwow);
			WindowManager wm = this.getWindowManager();
			int width = wm.getDefaultDisplay().getWidth();
			int height = wm.getDefaultDisplay().getHeight();
			mPopupWindow = new PopupWindow(exam_popunwindwow, width - 10,
					height / 2, true);
			mPopupWindow.setFocusable(true);
			mPopupWindow.setOutsideTouchable(true);
			// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable());

			mPopupWindow.showAtLocation(findViewById(R.id.examination),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		} else {
			mPopupWindow.dismiss();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (colseFlag == 0) {
			Intent i = getBaseContext().getPackageManager()
					.getLaunchIntentForPackage(
							getBaseContext().getPackageName());
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
}
